package vip.xiaonuo.device.modular.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.device.modular.entity.BizCabinetInfo;
import vip.xiaonuo.device.modular.entity.BizCabinetType;
import vip.xiaonuo.device.modular.mapper.CabinetDoorMapper;
import vip.xiaonuo.device.modular.mapper.CabinetInfoMapper;
import vip.xiaonuo.device.modular.mapper.CabinetTypeMapper;
import vip.xiaonuo.device.modular.mapper.GoodsLedgerMapper;
import vip.xiaonuo.device.modular.service.TokenService;
import vip.xiaonuo.device.vo.CabinetBindingVO;
import vip.xiaonuo.device.vo.CabinetScreenDoorVO;
import vip.xiaonuo.device.vo.CabinetScreenGoodsLedgerVO;
import vip.xiaonuo.device.vo.Result;

import javax.annotation.Resource;

/**
 * @author kongxm
 * @since 2023/2/8
 */
@Service("deviceBindingService")
public class DeviceBindingServiceImpl extends DeviceBaseService {

    @Resource
    private CabinetInfoMapper cabinetInfoMapper;
    @Resource
    private CabinetTypeMapper cabinetTypeMapper;
    @Resource
    private TokenService tokenService;

    @Override
    protected Integer getReqType() {
        return null;
    }

    @Override
    protected Boolean getLogFlag() {
        return false;
    }

    @Override
    protected Result handle(JSONObject param) {
        JSONObject data = param.getJSONObject("data");
        String cabinetId = data.getString("cabinetId");
        String cabinetIdentify = data.getString("cabinetIdentify");
        BizCabinetInfo bizCabinetInfo = cabinetInfoMapper.selectOne(new LambdaQueryWrapper<BizCabinetInfo>()
                .eq(BizCabinetInfo::getId, cabinetId)
                .last("limit 1"));
        if (bizCabinetInfo == null) return Result.fail("cabinetId不存在");
        if (StringUtils.isEmpty(bizCabinetInfo.getCabinetIdentify())) return Result.fail("硬件标识未登记");
        if (!bizCabinetInfo.getCabinetIdentify().equals(cabinetIdentify)) return Result.fail("硬件标识不匹配");
        CabinetBindingVO vo = CabinetBindingVO.builder()
                .postToken(tokenService.getToken())
                .cabinetCode(bizCabinetInfo.getCabinetCode())
                .build();
        if (bizCabinetInfo.getCabinetTypeId() != null) {
            BizCabinetType bizCabinetType = cabinetTypeMapper.selectById(bizCabinetInfo.getCabinetTypeId());
            if (bizCabinetType != null) vo.setCabinetType(bizCabinetType.getModel());
        }
        // 0-物品 1-试剂
        if (bizCabinetInfo.getCabinetInfoType() == 0) {
            vo.setCabinetCategory("WPG");
        } else if (bizCabinetInfo.getCabinetInfoType() == 1) {
            vo.setCabinetCategory("SJG");
        }

        return Result.ok(vo);
    }
}
